package cj.com.chabaike.ui.frag;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.tumblr.bookends.Bookends;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.InjectView;
import cj.com.chabaike.R;
import cj.com.chabaike.bll.PandaPagerManager;
import cj.com.chabaike.bll.RWServer;
import cj.com.chabaike.dao.FetchJSONDAO;
import cj.com.chabaike.entity.EliteList;
import cj.com.chabaike.entity.HomeData;
import cj.com.chabaike.entity.NewsData;
import cj.com.chabaike.entity.NewsList;
import cj.com.chabaike.ui.act.MainPager;
import cj.com.chabaike.ui.adapter.BaseRecyclerAdapter;
import cj.com.chabaike.ui.utils.HttpBitMapHelp;
import cj.com.chabaike.ui.utils.Navigator;
import cj.com.chabaike.ui.view.RecyclerLoaderFooter;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;

/**
 * Created by CJLAB on 2015/8/13.
 */
public class Recycler_NewsType_Fragment extends Fragment implements WaveSwipeRefreshLayout.OnRefreshListener {

    /**
     * ***************全局对象声明区*******************************
     */

    private List<NewsList> newsListlist;//Recycler数据源
    private Bundle tagBundle;
    private int tag_type; //用于控制获取的数据是哪个页面的
    private BitmapUtils bitmapUtils;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout; //这个是下拉刷新的控件
    private NewsDataRecyclerAdapter mNewsDataRecyclerAdapter; //Recycler适配器
    private Bookends<NewsDataRecyclerAdapter> mBookends; //用于添加RecylcerView头部和脚部
    private RecyclerLoaderFooter footer; //用于获得底部视图的管理类
    private View footerLoadView;
    private RecyclerView mRecyclerView;
    private RWServer rws; //服务类
    private PandaPagerManager ppm;

    /******************全局对象声明区结束********************************/

    /**
     * ******************生命周期方法区*******************************
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            tagBundle = getArguments();
        } else {
            tagBundle = savedInstanceState;
        }
        tag_type = tagBundle.getInt("tag_type");
        newsListlist = new ArrayList<>();
        bitmapUtils = HttpBitMapHelp.getBitmapUtils(getActivity().getApplicationContext());

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        rws = RWServer.getInstance(activity);
        ppm = PandaPagerManager.getPandaPagerManagerInstance();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mfrag1, null, false);
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE); //设置转动圈的颜色
        mWaveSwipeRefreshLayout.setOnRefreshListener(this); //刷新监听器

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置RecylerView的布局模式为垂直
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(layoutManager);


        mNewsDataRecyclerAdapter = new NewsDataRecyclerAdapter();
        mNewsDataRecyclerAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<NewsList>() {
            @Override
            public void onItemClick(View view, NewsList item, boolean isLongClick) {
                if (!isLongClick) {
                    Navigator.launchDetailNews(MainPager.of(getActivity()), view, item, MainPager.of(getActivity()).fragmentBackround);
                }
            }
        });


        footer = new RecyclerLoaderFooter(getActivity().getApplicationContext());
        footerLoadView = footer.getFootView(mRecyclerView, mWaveSwipeRefreshLayout, new RecyclerLoaderFooter.IFooterBtndown() {
            @Override
            public void whileFootBtnDown() {
                doLoadMore();
            }
        });


        mBookends = new Bookends<>(mNewsDataRecyclerAdapter);
        mBookends.addFooter(footerLoadView);
        mRecyclerView.setAdapter(mBookends);

        mWaveSwipeRefreshLayout.setRefreshing(true);
        footer.FooterBtnVisable(false);
        onRefresh();

        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState = tagBundle;
        super.onSaveInstanceState(outState);
    }


    /*********************生命周期方法区结束********************************/

    /*********************init区********************************/

    /*********************init区结束********************************/

    /**
     * ******************方法调用区*******************************
     */


    private void doLoadMore() { //加载更多
        footer.FooterBtnVisable(false);
        rws.getNewsData(ppm.getNewsTypeUrl_NextPager(tag_type), new FetchJSONDAO.NewsDataResultBack() {
            @Override
            public void newsResultWhat(boolean isSuccusful, NewsData newsData) {
                if (isSuccusful) {

                    if(newsData.getCode().equals("001")){
                        Log.w("加载" , ppm.getNewsTypeUrl_NextPager(tag_type));
                        Toast.makeText(getActivity(),"加载失败",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    newsListlist.addAll(newsData.getHome_page().getList());
                    PandaPagerManager.newsCurrenPager[tag_type]++;


                    updateRecylcerDate();

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            footer.FooterBtnVisable(true);
                            mWaveSwipeRefreshLayout.setRefreshing(false);
                            Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
                        }
                    }, 1000);

                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            footer.FooterBtnVisable(true);
                            mWaveSwipeRefreshLayout.setRefreshing(false);
                            Toast.makeText(getActivity(), "加载失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }, 1000);



                }
            }

        });

    }


    @Override
    public void onRefresh() {//下拉刷新
        rws.getNewsData(ppm.getNewsTypeUrl_FirstPager(tag_type), new FetchJSONDAO.NewsDataResultBack() {
            @Override
            public void newsResultWhat(boolean isSuccusful, NewsData newsData) {
                if (isSuccusful) {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mWaveSwipeRefreshLayout.setRefreshing(false);
                        }
                    }, 1000);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
                        }
                    }, 1800);

                    newsListlist.clear();
                    newsListlist.addAll(newsData.getHome_page().getList());
                    footer.FooterBtnVisable(true);
                    updateRecylcerDate();
                } else {
                    mWaveSwipeRefreshLayout.setRefreshing(false);
                    footer.FooterBtnVisable(true);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "加载失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }, 800);


                }
            }

        });


    }


    public void updateRecylcerDate() {
        mNewsDataRecyclerAdapter.updateList(newsListlist);
        mBookends.notifyDataSetChanged();

    }

    /*********************方法调用区结束********************************/

    /**
     * ******************内部类区*******************************
     */


    /*recylcerView的适配器 使用带有cardView的适配器 第二层继承*/

    class NewsDataRecyclerAdapter extends BaseRecyclerAdapter<NewsList> {

        @Override
        public ThingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recylcer_item_newstype, parent, false);
            return new ThingHolder(view);
        }


        public class ThingHolder extends BaseRecyclerAdapter<NewsList>.ViewHolder {
            @InjectView(R.id.item_news_title)
            TextView titleTextView;

            @InjectView(R.id.item_news_ItemViewKeyWord)
            TextView keyWorldTextView;

            @InjectView(R.id.item_news_commentNum)
            TextView commentNumTextView;

            @InjectView(R.id.item_news_ItemViewImg0)
            ImageView ItemViewImg;


            public ThingHolder(View itemView) {
                super(itemView);
            }

            public void populate(NewsList item) {
                titleTextView.setText(item.getTitle());
                commentNumTextView.setText(item.getCommentNum());
                keyWorldTextView.setText(getTimedata(item.getCreatedDate()));

                if (item.getImgurl().length()>0) {
                    bitmapUtils.display(ItemViewImg, item.getImgurl());

                }

            }

            private String getTimedata(String createDate) {
                Calendar c = Calendar.getInstance();
                int newsYear = 0, newsMonth = 0, newsDay = 0, newsHour = 0, newsMin = 0;
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH) + 1;
                int day = c.get(Calendar.DAY_OF_MONTH)-10;
                int hour = c.get(Calendar.HOUR_OF_DAY);
                int min = c.get(Calendar.MINUTE);

                try {
                    newsYear = Integer.parseInt(createDate.substring(0, 4));
                   // Log.e("newsYear", "" + newsYear);
                    newsMonth = Integer.parseInt(createDate.substring(6, 7));
                   // Log.e("newsMonth", "" + newsMonth);
                    newsDay = Integer.parseInt(createDate.substring(9, 10));
                   // Log.e("newsDay", "" + newsDay);
                    newsHour = Integer.parseInt(createDate.substring(12, 13));
                   //Log.e("newsHour", "" + newsHour);
                    newsMin = Integer.parseInt(createDate.substring(15, 16));
                   // Log.e("newsMin", "" + newsMin);
                } catch (Exception e) {
                   // Log.e("getTimedata", "截取json时间出错");
                  //  e.printStackTrace();
                }
                if (year - newsYear > 0) {
                    return "很久很久之前";

                } else if (month - newsMonth > 0) {
                    return (month - newsMonth) + "个月前";
                } else if (day - newsDay > 0) {
                    return (day - newsDay) + "天前";
                } else if (hour - newsHour > 0) {
                    return (hour - newsHour) + "小时前";
                } else if (min - newsMin > 0) {
                    return (min - newsMin) + "分钟前";
                }

                return "不知道多久之前";
            }

        }
    }


    /*********************内部类区结束********************************/


}
